-- Calculate the so called characteristic vector(s) for malware
-- files. Hhave a look at [International Journal of Hybrid Information
-- Technology, 2009, 2, 25-36], they used something similar.  This
-- characteristic vector will be used in future to categorise malware.
module Hexena.Cmds.CalcCV (run) where

import Data.Array.Unboxed
import qualified Data.ByteString.Lazy as L
import Data.Packed.Vector
import Data.Packed.Matrix
--import System.Environment (getArgs)
import Text.Printf

import Hexena.Math.Statistics

formatList :: [Double] -> [String]
formatList = map (printf "%13.7e")

formatProbs :: Probabilities -> [String]
formatProbs = formatList . elems

output :: Histogram -> IO ()
output h = putStrLn $ printf "  %g\t%s" entro probs
  where probs = unwords $ formatProbs $ histToProbability h
        entro = calculateE h

runner :: String -> IO (Vector Double)
runner fname = do
  putStrLn $ printf "%s:" fname
  content <- L.unpack `fmap` L.readFile fname
  hist <- calcHist content
  histC <- calcHist $ rleBS content
  output hist
  output histC
  return $ fromList $ elems (histToProbability hist) ++ elems (histToProbability histC)


-- main :: IO ()
-- main = do mest <- (calcStdDev . fromRows) `fmap` (mapM run =<< getArgs)
--           let means = map fst mest
--               stddevs = map snd mest
--           putStrLn "MEAN/STDDEV:"
--           putStrLn $ printf "  %13d\t\t%s" (0::Int) $ unwords $ formatList means
--           putStrLn $ printf "  %13d\t\t%s" (0::Int) $ unwords $ formatList stddevs

run :: FilePath -> IO ()
run fn = do file <- runner fn
            let mest = calcStdDev $ asRow file 
                means = map fst mest
                stddevs = map snd mest
                --mest = (calcStdDev . fromRows) file
            putStrLn "MEAN/STDDEV:"
            putStrLn $ printf "  %13d\t\t%s" (0::Int) $ unwords $ formatList means
            putStrLn $ printf "  %13d\t\t%s" (0::Int) $ unwords $ formatList stddevs
